import React from 'react';
import fetch from 'isomorphic-fetch';
import HeaderNav from 'shared/components/HeaderNav';
// import Toast from 'antd-mobile/lib/toast';
import Menu from 'shared/components/Menu';
import { bindCoupon } from 'shared/commonFetch';
import { activitDetailAPi } from '../api';

import './index.less';


const getBodyExpression = /<body[^>]*>([\s\S]*)<\/body>/;

export default class ActivityDetail extends React.PureComponent {
  state = {
    content: ''
  }
  componentDidMount() {
    const { id } = this.props.match.params;

    if (!isMobile) {
      const { pathname } = __self.history.location
      if (pathname.indexOf('activityDetail') !== -1) {
        location.href = `${window.url}/promotion?active_id=${id}`;
        return;
      }
    }

    activitDetailAPi({ activity_id: id }).then(({ data: { url_mobile } }) => {
      fetch(`/image/activity${url_mobile}`)
        .then((response) => {
          return response.text()
        })
        .then((res) => {
          const contentHtml = res.match(getBodyExpression)
          const content = contentHtml && contentHtml[0];

          this.setState({ content }, () => {
            const couponbtnDom = document.querySelector('.couponbtn');
            if (couponbtnDom) {
              couponbtnDom.onclick = () => {
                const code = couponbtnDom.getAttribute('id')
                bindCoupon(code);
              }
            }
          });
        })
        .catch(function(ex) {
          console.log('parsing failed', ex)
        })
    })
  }

  render() {
    const { content } = this.state;
    return (
      [
        <HeaderNav key="HeaderNav" showSearch={false} title="活动详情" />,
        <div key="detail" className="active-detail" dangerouslySetInnerHTML={{__html: content}} />,
        <Menu key="menu" />
      ]

    )
  }
}